package com.gzy.studentsociety.web;

import com.gzy.studentsociety.dao.SocietyDao;
import com.gzy.studentsociety.dao.SocietyDaoImpl;
import com.gzy.studentsociety.dao.StudentDao;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.entity.Society;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet(name = "SocietyServlet", value = "/society/*")
public class SocietyServlet extends RouteServlet {
    private SocietyDao societyDao = new SocietyDaoImpl();
    private StudentDao studentDao = new StudentDaoImpl();

    @Override
    protected Class getMyClass() {
        return this.getClass();
    }
    public String mainIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 初始化社团列表
        List<Society> list = null;
        // 获取社团信息
        try {
            list = societyDao.getAllSociety();
        }catch (SQLException throwables) {
            throwables.printStackTrace();
            handleException(throwables, request, response);
        }

        // 给社团列表添加创建者信息
        list = list.stream().map(i -> {
            try{
                i.setCreator(studentDao.findById(i.getSociety_creator()));
            }catch (SQLException e){
                request.setAttribute("exception",e);
            }
            return i;
        }).collect(Collectors.toList());

        // list 添加到 request 中
        request.setAttribute("societies",list);
        // 转发到 mainIndex.jsp
        return "mainIndex";
        // request.getRequestDispatcher("/WEB-INF/jsp/mainIndex.jsp").forward(request,response);
    }

    public String addSociety(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String intro = request.getParameter("intro");

        // 创建 Society 对象
        Society society = new Society();
        society.setSociety_intro(intro);
        society.setSociety_name(name);
        society.setSociety_status(1);

        // 获取 session 中登录者作为创建者
        String number = (String)(request.getSession().getAttribute("student"));

        StudentDao studentDao = new StudentDaoImpl();
        SocietyDao societyDao = new SocietyDaoImpl();

        // 获取学生的 ID
        try {
            society.setSociety_creator(studentDao.findByNumber(number).getStudentId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            handleException(throwables, request, response);
            return null;  // 异常处理后，确保不继续执行
        }

        society.setSociety_create_date(new Date());

        int result = -1;
        try {
            result = societyDao.insertSociety(society);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            handleException(throwables, request, response);
            return null;  // 异常处理后，确保不继续执行
        }

        // 确保没有内容输出之后，再进行重定向
        if (!response.isCommitted()) {
            response.sendRedirect("/studentSociety/society/mainIndex");
            return null; // 重定向后不再继续执行
        }

        // 返回直接跳转
        return "direct";
    }

    public Object updateSociety(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        String idStr = req.getParameter("id");
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");
        Integer id = idStr != null ? Integer.valueOf(idStr):null;
        Society society = new Society();
        society.setSocietyId(id);
        society.setSociety_name(name);
        society.setSociety_intro(intro);

        Map<String,Object> map = new HashMap<String,Object>();
        Integer result = null;
        if(id == null){
            map.put("message","id错误");
        }else{
            try {
                result = societyDao.updateSociety(society);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                map.put("message",throwables);
            }
            map.put("message",result);
        }
        return map;
    }

    public Object changeStatus(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        String idStr = req.getParameter("id");
        String statusStr= req.getParameter("status");
        Integer id = Integer.valueOf(idStr);
        Integer status = Integer.parseInt(statusStr);
        Society society = new Society();
        society.setSocietyId(id);
        society.setSociety_status(status);

        int result = -1;
        try {
            result = societyDao.updateSociety(society);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            req.setAttribute("exception",throwables);
            return "error";
        }
        if(result == 1){
            return result;
        }else{
            HashMap<String,String> map = new HashMap<String,String>();
            map.put("message","错误修改");
            return map;
        }
    }
}